package com.sfj.system.controller;

import com.kaka.starter.control.dto.ResultBean;
import com.kaka.starter.token.service.TokenService;
import com.kaka.starter.token.util.HeaderUtils;
import com.sfj.system.dto.LoginDTO;
import com.sfj.system.exception.LoginException;
import com.sfj.system.service.func.FuncQueryService;
import com.sfj.system.service.jiekou.TongyiSerrvice;
import com.sfj.system.service.jiekou.TongyiUserInfo;
import com.sfj.system.service.userinfo.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author kaka
 * @Date 2025/06/28
 */
@Api(tags = "登录")
@RestController
@Slf4j
public class LoginController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private FuncQueryService funcQueryService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TongyiSerrvice tongyiSerrvice;

    @GetMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public ResultBean login(@RequestParam String code) throws IOException {
        try {
            TongyiUserInfo tongyiUserInfo = tongyiSerrvice.login(code);
            log.info("统一平台用户信息: {}",tongyiUserInfo.getUserName());
            Map<String, Object> loginMap = new HashMap<>();
            loginMap = userInfoService.login(tongyiUserInfo);
            log.info("JYDC用户信息: {}", loginMap);
            return ResultBean.succeed(loginMap);
        } catch (LoginException e) {
            return ResultBean.fail("登入失败 错误原因:"+e.getMessage());
        }
    }

    @GetMapping("/funcList")
    @ApiOperation(value = "用户菜单列表", notes = "用户菜单列表")
    public ResultBean funcList() {
        Map map = new HashMap<>(6);
        //map.put("userName",HeaderUtils.getUserName());
        //map.put("userId",HeaderUtils.getUserId());
        //map.put("groupIds",HeaderUtils.getUserGroupIds());
        //map.put("level",HeaderUtils.getUserLevel());
        //map.put("roleIds",HeaderUtils.getRoleId());

        map.put("funcList",funcQueryService.getMenuTreeByRole(HeaderUtils.getRoleId()));
        return ResultBean.succeed(map);
    }

    @GetMapping("/logout")
    @ApiOperation(value = "用户登出", notes = "用户登出")
    public ResultBean logout() {
        tokenService.destory(HeaderUtils.getUserId());
        return ResultBean.succeed();
    }
}
